package cadad.org.parsers;

import java.util.Iterator;
import java.util.List;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import cadad.org.models.Book;
import cadad.org.models.Item;

public class BookParser {

	public Book parse(String responseGetBody) {

		HtmlCleaner htmlCleaner = new HtmlCleaner();

		TagNode node = htmlCleaner.clean(responseGetBody);

		List divsList1 = node.getElementListByName(ParserConstants.DIV, true);

		Iterator iterDivs = divsList1.iterator();

		Book book = new Book();

		while (iterDivs.hasNext()) {
			TagNode divNode = (TagNode) iterDivs.next();

			String classValue = divNode.getAttributeByName(ParserConstants.CLASS);
			if (classValue != null) {
				if (classValue.equals(ParserConstants.AVLBLK)) {

					List<TagNode> divChilds = divNode.getChildren();

					Iterator iterDivChilds = divChilds.iterator();

					while (iterDivChilds.hasNext()) {

						TagNode child = null;
						child = (TagNode) iterDivChilds.next();

						if (child.hasAttribute(ParserConstants.ID)) {
							if ((child.getAttributeByName(ParserConstants.ID).equals(ParserConstants.TTABLE1)) || (child.getAttributeByName(ParserConstants.ID).equals(ParserConstants.TTABLE2))) {
								ItemParser itemParser = new ItemParser();
								Item item = new Item();
								item = itemParser.parse(child);

								if (item.type.equals(ParserConstants.IDA)) {
									book.setFromItem(item);
								} else {
									book.setToItem(item);
								}
							}
						}
					}
				}
			}
		}

		return book;

	}

}
